//Ken edit, changed all visibility of fields that had no visibility constraints to protected

package com.livestocksolutions.ui;

import javax.swing.JOptionPane;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.Color;

import javax.swing.JLabel;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;

import javax.swing.BoxLayout;

import com.livestocksolutions.Bovine;
import com.livestocksolutions.FeedHistory;
import com.livestocksolutions.LivestockSolutions;
import com.livestocksolutions.MedicalHistory;
import com.livestocksolutions.MedicineHistory;
import com.livestocksolutions.util.JDatePickerDate;
import com.livestocksolutions.util.Table;

import javax.swing.JButton;
import javax.swing.border.MatteBorder;

/**
 * 
 * @author Matt Lang
 *
 */
public class IncomePanel extends JPanel {

	/**
	 * ID generated for serialization
	 */
	private static final long serialVersionUID = -514632476715036462L;
	protected JPanel displayPanel = new JPanel();
	protected final JDatePickerDate dateStart = JDatePickerDate.createJDatePicker();
	protected final JDatePickerDate dateEnd = JDatePickerDate.createJDatePicker();
	
	/**
	 * Constructor
	 */
	public IncomePanel() 
	{
		setLayout(new BorderLayout(0, 0));
		
		JPanel panel = new JPanel();
		add(panel, BorderLayout.NORTH);
		
		JLabel lblIncomePanel = new JLabel("Income Panel");
		lblIncomePanel.setFont(new Font("Tahoma", Font.BOLD, 20));
		panel.add(lblIncomePanel);
		
		JPanel panel_1 = new JPanel();
		add(panel_1, BorderLayout.CENTER);
		panel_1.setLayout(new BorderLayout(0, 0));
		
		JPanel panel_2 = new JPanel();
		panel_1.add(panel_2, BorderLayout.NORTH);
		panel_2.setLayout(new BoxLayout(panel_2, BoxLayout.X_AXIS));
		
		JButton btnGenerateReport = new JButton("Generate Report");
		panel_2.add(btnGenerateReport);
		
		JPanel panel_3 = new JPanel();
		panel_1.add(panel_3, BorderLayout.CENTER);
		panel_3.setLayout(new BorderLayout(0, 0));
		
		
		panel_3.add(displayPanel, BorderLayout.CENTER);
		
		
		panel_2.add(new JLabel("Start Date:"));
		panel_2.add(dateStart);
		panel_2.add(new JLabel("End Date:"));
		panel_2.add(dateEnd);
		
		btnGenerateReport.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				if(dateStart.getDate()==null ||dateEnd.getDate()==null)
					outputDateErrorMessage();
				else
					updatePanel(dateStart.getDate(), dateEnd.getDate());
			}
		});
		
	}
	
	/**
	 * Show an error message to the user when start and end date are invalid.
	 */
	protected static void outputDateErrorMessage() {
		JOptionPane.showMessageDialog(MainFrame.getInstance(),"Please enter both start and end date","Invalid Dates", JOptionPane.OK_OPTION);
	}

	/**
	 * Update the list to calculate income between the given dates.
	 * @param startDate The date to start the transactions by.
	 * @param endDate The date to end the transactions by.
	 */
	public void updatePanel(Date startDate, Date endDate)
	{
		ArrayList<Bovine> bovines = new ArrayList<Bovine>(Arrays.asList(LivestockSolutions.getBovines()));
		NumberFormat formatter = NumberFormat.getCurrencyInstance();
		Iterator<Bovine> i = bovines.iterator();
		Table updatePanel = new Table("Income from bovines sold between "+JDatePickerDate.format(startDate)+" and "+JDatePickerDate.format(endDate), true,
				"Visual ID", "Feed Expenses","Medicine Expenses", "Vet Expenses", "Sell Price", "Net Income");
		updatePanel.setHeaderClickable(0, false);
		updatePanel.setHeaderClickable(1, false);
		updatePanel.setHeaderClickable(2, false);
		updatePanel.setHeaderClickable(3, false);
		updatePanel.setHeaderClickable(4, false);
		updatePanel.setHeaderClickable(5, false);
		double totalMedical, totalFeed, totalMedicine, totalSellPrice;
		totalMedical = totalFeed = totalMedicine = totalSellPrice = 0;
		while(i.hasNext())
		{
			Bovine b = i.next();
			if(b.getDeacquisition()!=null&&b.getDeacquisition().getMethod().toLowerCase().equals("sold")&&b.getDeacquisition().getDate().before(endDate)
					&&b.getDeacquisition().getDate().after(startDate))
			{
				double sellPrice, medicalExpenses, medicineExpenses, feedExpenses;
				sellPrice = medicalExpenses = medicineExpenses = feedExpenses = 0;
				sellPrice = b.getDeacquisition().getPrice();
				MedicalHistory[] medicals = b.getMedicals();
				FeedHistory[] feeds = b.getHandFeeds();
				MedicineHistory[] medicines = b.getMedicines();
				for(int i1=0;i1<medicals.length;i1++)
				{
					medicalExpenses += medicals[i1].getCost();
				}
				for(int i1=0;i1<feeds.length;i1++)
				{
					feedExpenses += feeds[i1].getCost();
				}
				for(int i1=0;i1<medicines.length;i1++)
				{
					medicineExpenses += medicines[i1].getCost();
				}
				totalFeed += feedExpenses;
				totalMedical += medicalExpenses;
				totalMedicine += medicineExpenses;
				totalSellPrice += sellPrice;
				
				updatePanel.addRow(new JLabel(b.getEartag().getEartagID()), new JLabel(String.valueOf(formatter.format(feedExpenses))),
						new JLabel(String.valueOf(formatter.format(medicineExpenses))), new JLabel(String.valueOf(formatter.format(medicalExpenses))),
						new JLabel(String.valueOf(formatter.format(sellPrice))), new JLabel(String.valueOf(formatter.format(sellPrice -(medicalExpenses+medicineExpenses+feedExpenses)))));
				
				final long id = b.getID();
				updatePanel.addMouseListener(new MouseListener() {
					@Override
					public void mouseClicked(MouseEvent arg0) {
						if(MainFrame.getInstance().showBovine(id)) {
						}
					}
					@Override public void mouseEntered(MouseEvent arg0) {}
					@Override public void mouseExited(MouseEvent arg0) {}
					@Override public void mousePressed(MouseEvent arg0) {}
					@Override public void mouseReleased(MouseEvent arg0) {}
				});
			}
			
		}
		if(updatePanel.getNumRows() != 0)
		{
			updatePanel.addRow(new JLabel("Totals"), new JLabel(String.valueOf(formatter.format(totalFeed))),
					new JLabel(String.valueOf(formatter.format(totalMedicine))), new JLabel(String.valueOf(formatter.format(totalMedical))),
					new JLabel(String.valueOf(formatter.format(totalSellPrice))), new JLabel(String.valueOf(formatter.format(totalSellPrice -(totalMedical+totalMedicine+totalFeed)))));
			updatePanel.setRowClickable(false);
			updatePanel.setRowBorder(new MatteBorder(1,0,0,0,Color.black));
		}
		updatePanel.setEmptyMessage("No Cattle sold within the given period");
		displayPanel.add(updatePanel);
	}
}
